3. 组件/jsx初探

主要介绍React中的组件,与Vue中的组件概念大致一致。但是写法却大不同。React中使用js中面向对象的思想来编写组件。

/src/index.js

1
2
3
4
5
6
7
8
9
10
// 下方虽没有引用,但是不可省略,因为jsx中会用到
import React from 'react';

import ReactDOM from 'react-dom';

// 引入App.js(组件)
import App from './App';

// 将App组件渲染到root节点
ReactDOM.render(<App />, document.getElementById('root'));

/src/App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// { Component } 是ES6中的解构赋值的写法,代码的意思是导入react.Component。同理这里也不能去掉React
import React, { Component } from 'react';

// 当一个类集成了React的Component,那么他就是一个React的组件
class App extends Component {
render() {
// jsx
return (
<div>
Hello World!
</div>
)
}
}
export default App;

JSX

1
jsx:在js中写html。在jsx中,组件必须以大写字母开头。其他的小写标签为html标签。